<template>
    <div class="coupon-list-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                </div>
                <div class="header-right">
                    <el-button type="primary" @click="handleAddCoupon">新增优惠券</el-button>
                </div>
            </div>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="name" label="优惠券名" />
                    <el-table-column label="优惠券满减">
                        <template #default="{ row }">
                            {{ formatCouponCondition(row) }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="amount" label="优惠券金额" align="right">
                        <template #default="{ row }">
                            ¥{{ row.amount }}
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="totalQuantity" label="数量" align="center">
                        <template #default="{ row }">
                            {{ formatQuantity(row.totalQuantity) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ pagination.total }}条记录,当前在第{{ pagination.currentPage }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.currentPage"
                        v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="pagination.total"
                        layout="sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange"
                        @current-change="handlePageChange"
                    />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { formatTime } from '@/utils/time';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Coupon, CouponQueryParams } from '@/types/coupon';
import { getCouponPage, deleteCoupon } from '@/api/member/coupon';

const router = useRouter();

// 表格数据
const loading = ref(false);
const tableData = ref<Coupon[]>([]);

// 分页数据
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
});

// 获取优惠券列表数据
const getData = async () => {
    loading.value = true;
    try {
        const params: CouponQueryParams = {
            current: pagination.currentPage,
            size: pagination.pageSize
        };
        
        console.log('请求参数:', params);
        
        const res = await getCouponPage(params);
        console.log('API响应:', res);
        
        const responseData = res as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || [];
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0;
            
            if (tableData.value.length === 0) {
                ElMessage.info('暂无优惠券数据');
            }
        } else {
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取优惠券数据失败';
            ElMessage.error(errorMsg);
            tableData.value = [];
            pagination.total = 0;
        }
    } catch (error) {
        console.error('获取优惠券数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
        tableData.value = [];
        pagination.total = 0;
    } finally {
        loading.value = false;
    }
};



// 格式化优惠券条件
const formatCouponCondition = (coupon: Coupon) => {
    if (coupon.discountType === 1) {
        // 满减券
        return `满${coupon.minAmount}减${coupon.discountValue}`;
    } else if (coupon.discountType === 2) {
        // 折扣券
        return `满${coupon.minAmount}享${coupon.discountValue}折`;
    } else if (coupon.discountType === 3) {
        // 免运费券
        return `免运费${coupon.discountValue}元`;
    }
    return '-';
};

// 数量格式化函数
const formatQuantity = (quantity: number) => {
    if (quantity === -1) {
        return '不限量';
    }
    return quantity.toString();
};

// 新增优惠券
const handleAddCoupon = () => {
    router.push('/coupon-form');
};


// 编辑优惠券
const handleEdit = (row: any) => {
    router.push(`/coupon-form/${row.id || '1'}`);
};

// 删除优惠券
const handleDelete = async (row: Coupon) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除优惠券 "${row.name}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        loading.value = true;
        const res = await deleteCoupon(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200) {
            ElMessage.success('删除成功');
            getData(); // 刷新列表
        } else {
            const errorMsg = (responseData && responseData.msg) || '删除失败';
            ElMessage.error(errorMsg);
        }
        
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除优惠券失败:', error);
            ElMessage.error('删除失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
};

// 分页处理
const handlePageChange = (page: number) => {
    pagination.currentPage = page;
    getData();
};

const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    pagination.currentPage = 1;
    getData();
};

// 页面初始化
onMounted(() => {
    getData();
});
</script>

<style scoped>
.coupon-list-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-right {
    display: flex;
    gap: 10px;
}

/* 表格区域样式 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

/* 分页区域 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
    padding: 20px;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 表格样式优化 */
:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.el-table th) {
    background-color: #fafafa;
    color: #606266;
    font-weight: 600;
}

:deep(.el-table td) {
    padding: 12px 0;
}

:deep(.el-table--border) {
    border: 1px solid #ebeef5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background: #fafafa;
}

/* 卡片样式 */
:deep(.el-card__body) {
    padding: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .coupon-list-container {
        padding: 10px;
    }
    
    .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .header-right {
        width: 100%;
        justify-content: flex-start;
    }
}
</style>
